/**
 * 
 */
package name.yzhu.httpserver.log;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import name.yzhu.httpserver.AbstractHttpServlet;
import name.yzhu.httpserver.HttpRequestType;
import name.yzhu.httpserver.HttpReturnData;

/**
 * @author yhzhu
 *
 */
public class BaseLogHandler implements LogHandler{
	static private final Log LOG = LogFactory.getLog(BaseLogHandler.class);
	
	protected HttpRequestType type;
	protected HttpServletRequest req;
	protected HttpReturnData retData;

	private long beginTime = 0;

	private long endTime = 0;

	public void begin(){
		this.beginTime = System.currentTimeMillis();
	}
	
	public void end(){
		this.endTime  = System.currentTimeMillis();
	}
	
	@Override
	public void setRequest(HttpServletRequest req) {
		this.req = req;
	}

	@Override
	public void setRetuData(HttpReturnData retData) {
		this.retData = retData;
	}

	@Override
	public void setRequestType(HttpRequestType type) {
		this.type = type;
	}

	@Override
	public HttpRequestType getRequestType() {
		return type;
	}

	@Override
	public LogEntity getLogEntity() {
		BaseLogEngity entity = new BaseLogEngity();
		
		return entity;
	}
	
	@Override
	public void persist(LogEntity entity){
		StringBuilder sb = new StringBuilder();
		sb.append("[Type: "+type.getName()+"] ");
		sb.append("[URL: http://"+req.getLocalName()+":"+req.getLocalPort()+req.getRequestURI());
		sb.append(AbstractHttpServlet.printQuery(req)+"] ");
		sb.append("[From "+req.getRemoteAddr()+"] ");
		sb.append("[Entity: "+entity+"] ");
		sb.append("[HTTP_Status: "+retData.getStatus()+"] ");
		sb.append("[cost: "+String.valueOf(endTime - beginTime) +" ms]");
		LOG.info(sb.toString());
	}
}
